<?php

namespace Home\Controller;

class BaseController extends \Think\Controller {

    protected $user_id = 0;   //用户ID

    public function _initialize() {
        $userTokenInfo = $this->isLogin();
        $this->user_id = $userTokenInfo['userId'];
        //用户状态判断
        if ($this->user_id) {
            $this->getUserStatus($userTokenInfo['userId']);
        }
    }

    /**
     * Ajax方式返回数据信息到客户端
     * @param mixed $iStatus 状态 bool 或 int 类型
     * @param string $iCode  返回状态码 
     * @param string $strMsg 描述信息 
     * @param mixed $data 要返回的数据 
     * @return void 
     */
    protected function ajaxReturn($iStatus, $strMsg = '', $data = '', $iCode = 0) {
        $arrData['success'] = $iStatus;
        $arrData['msg'] = $strMsg;
        $arrData['data'] = $data;
        $arrData['code'] = $iCode;
        parent::ajaxReturn($arrData);
    }

    /**
     * 成功返回
     * @return void 
     */
    protected function success($strMsg = '执行成功', $data = '', $iCode = 0) {
        $arrData['success'] = 1;
        $arrData['msg'] = $strMsg;
        $arrData['data'] = $data;
        $arrData['code'] = $iCode;
        parent::ajaxReturn($arrData);
    }

    /**
     * 失败返回
     * @return void 
     */
    protected function error($strMsg = '执行失败', $data = '', $iCode = 0) {
        $arrData['success'] = 0;
        $arrData['msg'] = $strMsg;
        $arrData['data'] = $data;
        $arrData['code'] = $iCode;
        parent::ajaxReturn($arrData);
    }

    /**
     * TODO 上传文件方法
     * @param $file_name form表单file的name值
     * @param $dir 上传到uploads目录的$dir文件夹里
     * @param int $maxsize 最大上传限制，默认1048576 byte = 10*1024*1024 byte = 10M
     * @param array $exts 允许上传文件类型 默认array('gif','jpg','jpeg','bmp','png')
     * @return array 返回array,失败status=0 成功status=1,filepath=newspost/2014-9-9/a.jpg
     */
    protected function uploadfile($file_name, $dir, $maxsize = 10485760, $exts = array('gif', 'jpg', 'jpeg', 'bmp', 'png')) {
        $upload = new \Think\Upload(); // 实例化上传类
        $upload->maxSize = $maxsize; // 设置附件上传大小，单位字节(微信图片限制1M
        $upload->exts = $exts; // 设置附件上传类型
        $upload->rootPath = './Uploads/'; // 设置附件上传根目录
        $upload->savePath = $dir . '/'; // 设置附件上传（子）目录
        // 上传文件
        if (empty($_FILES[$file_name])) {
            $this->ajaxReturn(0, "请选择上传图片");
        }

        $info = $upload->uploadOne($_FILES[$file_name]);

        if (!$info) {// 上传错误提示错误信息
            $this->ajaxReturn(0, $upload->getError());
        } else {// 上传成功
            return '/Uploads/' . $info['savepath'] . $info['savename'];
        }
    }

    /**
     * 判断用户是否登录
     */
    public function isLogin($isReturn = false) {
        //测试代码
        //$this->ajaxReturn(array('error' => 1, 'info' =>CONTROLLER_NAME));
        //判断是否忽略列表
//        $ignore = global_config('ignore_check_login');
//        if ($ignore) {
//            $ignore = split(',', $ignore);
//            if (in_array(API_CODE, $ignore))
//                return true;
//        }

        $result = array('error' => 1, 'info' => false);
        $param = I('params');

        $error = '';
        //判断是否传入user_token
        $userToken = $param['user_token'];
        if (I("user_token")) {
            $userToken = I("user_token");
        }
        if (!preg_match('/^\w{32,64}$/', $userToken)) {
            $result['info'] = '请传入user_token';
            $error = '请传入user_token';
        } else {
            //查询库
            $where['user_token'] = $userToken;
            $ut = M('Users')->where($where)->find();
//            $ut = $this->returnOne('Users', $where, '', 'user_id,user_token,phone');
//            dump($ut);die;
            if (!$ut) {
//                $result['info'] = '请登录';
//                $result['error'] = 2;
                $this->error('请登录', '', 101);
            }
        }

        //如果已登录则直接返回，否则输出到客户端
        if ($result['info'] === false) {
            return array('userId' => $ut['user_id'], 'userToken' => $ut['user_token'], 'phone' => $ut['phone']);
        }

        $this->ajaxReturn(0, $error);
    }

    //判断用户状态
    public function getUserStatus($user_id) {
        $objUser = M('Users');
        $userInfo = $objUser->field("status")->where(array('user_id' => $user_id))->find();

        if ($userInfo['status']) {
            $this->ajaxReturn(0, '您的账号已被禁用,请联系管理员', '', 110);
        }
    }

    /**
     * 查询信息
     * @param string $model 模型名称
     * @param array $where 查询条件
     * @param string $order 排序规则
     * @param string $field 返回字段信息
     * @author 刘新
     * @return array|boolean 返回查询结果
     */
    protected function returnOne($model, $where = array(), $order = '', $field = true) {
        //获取模型
        $model = $this->getModel($model);

        //构造查询条件
        if (!$where)
            $where = array('status' => 1);
        if (empty($where['status']) && $where['status'] !== 0 && $where['status'] !== '0')
            $where['status'] = 1;

        //查询并返回结果
        return $model->where($where)->order($order)->field($field)->find();
    }

    /**
     * 获取模型对象
     * @param string|object $model
     * @author 刘新
     */
    protected function getModel($model) {
        if (!$model)
            return M();
        if (is_string($model))
            return M($model);
        if (!is_object($model))
            return false;
        return $model;
    }

    /**
     * 错误日志
     * @param string $file 发生错误的文件
     * @param string|int $line 错误日志发生的等号
     * @author 刘新
     */
    public function errorLog($file, $line, $content) {
        record_error_log($file, $line, $content, $this->user['userId'], $this->user['phone']);
        /* 	if(is_object($content)) {
          $data['content'] = $content->getDbError() . '---' . $content->getError();
          } else {
          $data['content'] = $content;
          }
          $data['file'] = $file;
          $data['line'] = $line;
          $data['controller'] = CONTROLLER_NAME;
          $data['action'] = ACTION_NAME;
          $data['module'] = MODULE_NAME;
          $data['api_code']	= API_CODE;
          $data['user_id'] = $this->user['userId'];
          $data['phone'] = M('User')->where(array('id'=>$data['user_id']))->getField('phone');
          return D('ErrorLog')->addErrorLog($data); */
    }

    /**
     * 处理操作后返回的数据
     * @param array $data
     * @param string $info
     * @return array
     * @author 刘新
     */
    public function successResult($data, $info = '') {
        $return = array('error' => 0, 'info' => '');
        //有数据
        if ($data) {
            if ($info) {
                $return['info'] = $info;
            } else {
                $return['info'] = $data;
            }
            //无数据
        } else {
            $return['info'] = array();
        }

        return $return;
    }

    /**
     * 处理操作后返回的数据
     * @param array $data
     * @param string $info 查询成功且有数据时的提示信息
     * @return array
     * @author 刘新
     */
    public function result($data, $info = '') {
        if ($data === false)
            return array('error' => 1, 'info' => '查询失败');
        return $this->successResult($data, $info);
    }

}
